package com.ncmmall.mall.controller.business.withdraw;

import com.ncmmall.application.business.withdraw.MerchantWithdrawApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.domain.business.trading.MerchantWithdrawApply;
import com.ncmmall.domain.business.trading.QMerchantWithdrawApply;
import com.ncmmall.domain.business.trading.QTradingLog;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家提现结算管理
 *
 * @author likaikai
 * @date 2019-07-22 15:38:57
 */
@Controller
@RequestMapping("/mall/merchant/withdraw")
public class MerchantFinalController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantWithdrawApplication merchantWithdrawApplication;

    @Autowired
    private OperationLogApplication logApplication;

    private final Logger logger = LoggerFactory.getLogger(MerchantFinalController.class);

    /**
     * 结算申请列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, MerchantWithdrawApply params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());
        Map<String, Object> map = new HashMap<>();
        String sql = buildSql("select r from MerchantWithdrawApply r where 1 = 1 ", map, params);
        QueryPage<MerchantWithdrawApply> page = queryChannelService.findPage(sql, pageRequest.setParams(map), MerchantWithdrawApply.class);

        model.addAttribute("params", params);
        model.addAttribute("page", page);

        return "mall/final/merchant/list";
    }

    /**
     * 查看结算单明细
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        MerchantWithdrawApply apply = queryChannelService.findOne(QMerchantWithdrawApply.merchantWithdrawApply.id.eq(id), MerchantWithdrawApply.class);
        List<TradingLog> tradings = queryChannelService.findAll(QTradingLog.tradingLog.merchant.id.eq(apply.getMerchant().getId()), TradingLog.class);
        model.addAttribute("tradings", tradings);

        return "mall/final/merchant/details";
    }

    /**
     * 结算申请审核通过
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/pass", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> pass(HttpServletRequest request, @PathVariable("id") long id) {
        try {

            MerchantWithdrawApply apply = queryChannelService.findOne(QMerchantWithdrawApply.merchantWithdrawApply.id.eq(id), MerchantWithdrawApply.class);
            merchantWithdrawApplication.applyPass(apply);

            logApplication.eventOfSystem(Securitys.currentUser(), "商家结算审核通过", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[商户结算申请审核通过异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }
    }

    /**
     * 结算申请审核被拒绝
     *
     * @param params
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reject", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> reject(HttpServletRequest request, MerchantWithdrawApply params, @PathVariable("id") long id) {
        try {

            params.setId(id);
            merchantWithdrawApplication.applyReject(params);

            logApplication.eventOfSystem(Securitys.currentUser(), "商家结算审核拒绝", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[商户结算申请审核拒绝异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }
    }

    /**
     * 结算完成
     *
     * @param params
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/finish", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> finish(HttpServletRequest request, MerchantWithdrawApply params, @PathVariable("id") long id) {
        try {

            params.setId(id);
            merchantWithdrawApplication.finish(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "完成结算", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[商户结算申请审核拒绝异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param map
     * @param params
     * @return
     */
    private String buildSql(String sql, Map<String, Object> map, MerchantWithdrawApply params) {

        if (params.getStatus() > 0) {
            sql += " and r.status = :status";
            map.put("status", params.getStatus());
        }

        sql += " order by r.applyTime desc";

        return sql;
    }


}
